/* eslint-disable no-script-url */
/*
 * @Author: your name
 * @Date: 2021-08-25 08:57:05
 * @LastEditTime: 2021-08-31 09:47:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \mobile-h5\src\features\tableList\table\Table.tsx
 */
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { history } from '@library';
import qs from 'query-string';
import { ListView } from 'antd-mobile';
import { getSource } from '../../api';
import { sessionStorageKey } from '../../config';
// import { history } from '../../../../app/routes';
import Icon from '../../components/icon/Icon';
import styles from './table.module.scss';

const iconStyle = { marginLeft: '12px' };
const listStyle = {
  flex: '1 1',
  background: '#fff',
};
const footerStyle: React.CSSProperties = { padding: 30, textAlign: 'center' };
const pageSize = 20;
const renderColumns = 5;

const getQuery = (query: string, page: number, fuzzyField: string, fuzzyValue: string) => {
  return {
    fuzzyField: fuzzyValue ? [fuzzyField] : undefined,
    fuzzyValue: fuzzyValue || undefined,
    fuzzyQuery: !!fuzzyValue ? true : undefined,
    pages: { pageSize, page },
    ...JSON.parse(query),
  };
};

export default () => {
  const query = qs.parseUrl(window.location.href).query;

  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [fuzzyValue, setFuzzyValue] = useState('');

  const [hasMore, setHasMore] = useState(true);
  const [showSearch, setShowSearch] = useState(false);
  const [glist, setGlist] = useState<any[]>([]);

  const ds = useRef(
    new ListView.DataSource({
      rowHasChanged: () => true,
    })
  );

  const [dataSource, setDataSource] = useState(ds.current);

  const onRequestMore = useCallback(
    async (event?: Event) => {
      if (!hasMore) {
        setLoading(false);
        return;
      }
      setLoading(true);
      const res = await getSource(query.url as string, getQuery(query.query as string, page, query.fuzzyField as string, fuzzyValue));

      setPage(page + 1);
      if (res.rows.length !== pageSize) {
        setHasMore(false);
      }
      setGlist([...glist, ...(res.rows || [])]);
      setDataSource(dataSource.cloneWithRows([...glist, ...(res.rows || [])]));
      setLoading(false);
    },
    [dataSource, fuzzyValue, glist, hasMore, page, query]
  );

  const onRequestSearch = useCallback(
    async (fuzzyValue: string) => {
      setLoading(true);
      const res = await getSource(query.url as string, getQuery(query.query as string, 1, query.fuzzyField as string, fuzzyValue));
      setPage(2);
      if (res.rows.length !== pageSize) {
        setHasMore(false);
      } else {
        setHasMore(true);
      }
      setGlist([...(res.rows || [])]);
      setDataSource(dataSource.cloneWithRows([...(res.rows || [])]));
      setLoading(false);
    },
    [dataSource, query]
  );

  useEffect(() => {
    onRequestMore();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const renderItem = useCallback(
    (rowData: any, sectionID: any, rowID: any) => {
      let fuzzyField = query.fuzzyField as string;

      let filedShowName = JSON.parse(sessionStorage.getItem(sessionStorageKey['filedShowName']) || '[]');

      let index = filedShowName.findIndex((item: any) => item.value === fuzzyField);
      if (index >= 0) {
        filedShowName.splice(index, 1);
      }
      filedShowName.splice(0, 0, { value: fuzzyField });

      return (
        <div
          key={rowID}
          onClick={() => {
            sessionStorage.setItem(sessionStorageKey['lov_data'], JSON.stringify(rowData));
            history.back();
          }}
        >
          <div className={styles.item}>
            {filedShowName.map((item: any, index: number) => (index <= renderColumns - 1 ? <div key={item.value}>{rowData[item.value]}</div> : null))}
          </div>
        </div>
      );
    },
    [query.fuzzyField]
  );

  const onKeyDown = useCallback(
    (code: number) => {
      if (code === 13) {
        let value = (document.getElementById('search') as any)?.value;
        setShowSearch(false);
        setFuzzyValue(value);
        onRequestSearch(value);
      }
    },
    [onRequestSearch]
  );

  return (
    <div className={styles.tableList}>
      <div className={styles.header}>
        <div onClick={() => setShowSearch(true)}>
          <label htmlFor="search">
            <Icon icon="&#xe63b;" style={iconStyle} /> {fuzzyValue || '搜索'}
          </label>
        </div>
      </div>
      <div className={styles.search} style={showSearch ? { zIndex: 9999 } : { zIndex: -2 }}>
        <div className={styles.header}>
          <Icon icon="&#xe63b;" className={styles.iconsearch} />

          <form
            onSubmit={(e) => {
              e.preventDefault();
              return false;
            }}
          >
            {showSearch && <input type="search" id="search" onKeyDown={(e) => onKeyDown(e.keyCode)} autoFocus placeholder="请输入搜索条件" />}
          </form>
          <div onClick={() => setShowSearch(false)}>取消</div>
        </div>
      </div>
      <ListView
        dataSource={dataSource}
        renderRow={renderItem}
        renderFooter={() => <div style={footerStyle}>{loading ? '加载中...' : '没有更多数据了...'}</div>}
        pageSize={pageSize}
        initialListSize={pageSize}
        onEndReached={onRequestMore}
        onEndReachedThreshold={100}
        style={listStyle}
      />
    </div>
  );
};
